import type {IHooksOptions} from '@/hooks/interface'
import service from '@/utils/request'
import {onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'

export const useCrud = (options: IHooksOptions) => {
    const defaultOptions: IHooksOptions = {
        createdIsNeed: true,
        dataListUrl: '',
        isPage: true,
        deleteUrl: '',
        primaryKey: 'id',
        exportUrl: '',
        queryForm: {},
        dataList: [],
        orderField: '',
        asc: false,
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [1, 10, 20, 50, 100, 200],
        dataListLoading: false,
        dataListSelections: [],
        deleteCallBack(id: number | string) {
            console.log("删除后回调")
        }
    }

    const mergeDefaultOptions = (options: any, props: any): IHooksOptions => {
        for (const key in options) {
            if (!Object.getOwnPropertyDescriptor(props, key)) {
                props[key] = options[key]
            }
        }
        return props
    }

    // 覆盖默认值
    const state = mergeDefaultOptions(defaultOptions, options)

    onMounted(() => {
        if (state.createdIsNeed) {
            query()
        }
    })

    const query = () => {
        if (!state.dataListUrl) {
            return
        }

        state.dataListLoading = true

        service
            .post(state.dataListUrl, {
                orderField: state.orderField,
                asc: state.asc,
                pageIndex: state.isPage ? state.pageIndex : 1,
                pageSize: state.isPage ? state.pageSize : 1000,
                data: {
                    ...state.queryForm
                }
            })
            .then((res: any) => {
                if (state.isPage) {
                    state.dataList = res.data.list;
                } else {
                    if (Array.prototype.isPrototypeOf(res.data)) {
                        state.dataList = res.data;
                    } else {
                        state.dataList = res.data.list;
                    }
                }
                state.total = state.isPage ? res.data.total : 0
            })

        state.dataListLoading = false
    }

    const getDataList = () => {
        state.pageIndex = 1
        query()
    }

    const sizeChangeHandle = (val: number) => {
        state.pageIndex = 1
        state.pageSize = val
        query()
    }

    const currentChangeHandle = (val: number) => {
        state.pageIndex = val
        query()
    }

    // 多选
    const selectionChangeHandle = (selections: any[]) => {
        state.dataListSelections = selections.map((item: any) => state.primaryKey && item[state.primaryKey])
    }

    // 排序
    const sortChangeHandle = (data: any) => {
        const {prop, order} = data

        if (prop && order) {
            state.orderField = prop
            state.asc = order === 'ascending'
        } else {
            state.orderField = ''
        }

        query()
    }

    //单个删除
    const deleteHandle = (key: number | string, data?: any) => {
        if (!state.deleteUrl) {
            return
        }

        ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                service.delete(state.deleteUrl + '/' + key).then(() => {
                    ElMessage.success('删除成功')
                    if (state.deleteCallBack) {
                        state.deleteCallBack(key, data);
                    }
                    query()
                })
            })
            .catch(() => {
            })
    }

    //批量删除
    const deleteBatchHandle = (key?: number | string) => {
        let data: any[] = []
        if (key) {
            data = [key]
        } else {
            data = state.dataListSelections ? state.dataListSelections : []

            if (data.length === 0) {
                ElMessage.warning('请选择删除记录')
                return
            }
        }

        ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                if (state.deleteUrl) {
                    service.post(state.deleteUrl, {data}).then(() => {
                        ElMessage.success('删除成功')

                        query()
                    })
                }
            })
            .catch(() => {
            })
    }

    //序号
    const pagerIndex = (scope: { $index: number }) => {
        if (state.pageIndex && state.pageSize) {
            return scope.$index + (state.pageIndex - 1) * state.pageSize + 1
        } else {
            return 0;
        }
    };

    return {
        getDataList,
        sizeChangeHandle,
        currentChangeHandle,
        selectionChangeHandle,
        sortChangeHandle,
        deleteHandle,
        deleteBatchHandle,
        pagerIndex,
        query
    }
}
